<?php

namespace app\controller;

use app\BaseController;
use app\Request;
use think\facade\Db;
use think\facade\Log;
use Vonage\Client\Credentials\Basic;

class Adv
{

    public function index(Request $request)
    {
        $id = $request->param('id');
        $usercode = $request->param('usercode');
        if ($id == '') {
            Log::write('打开页面,无id,usercode参数:' . json_encode($request->param()));
            echo '异常页面';
            die;
        }
        $data = Db::table('page')->where('keys', $id)->find();
        $kefu_arr = json_decode($data['kefu']);
        $url = $kefu_arr[array_rand($kefu_arr)];

        $add_id = Db::table('page_log')->insertGetId([
            'usercode' => $usercode,
            'page_keys' => $id,
            'url' =>  $request->domain() . $request->url(),
            'ip' => $request->ip(),
            'create_time' => time()
        ]);

        $user_arr = Db::table('user')->where('usercode', $usercode)->find();
        if (!$user_arr) {
            $appid = 0;
        } else {
            $appid = $user_arr['appcode'];
        }
        Log::write('打开页面:' . $appid . '+' . json_encode($request->param()), 'info');
        
        $apilogid = Db::table('api_log')->insertGetId([
            'code' => $add_id,
            'url' => $request->domain() . $request->url(),
            'result' => 'b面',
            'create_time' => time()
        ]);

        return view($data['template_id'], ['code' => $id,  'appid' => $appid,'add_id'=>$add_id, 'url' => $url,'usercode'=>$usercode]);
    }
    /**
     * 点击监控
     */
    public function click(Request $request) //$id, $button, $aid, $appid = '')
    {
        $id = $request->param('id');
        $button = $request->param('button');
        $aid = $request->param('aid');
        $appid = $request->param('appid');
        $data = Db::table('page')->where('keys', $id)->find();
        $kefu_arr = json_decode($data['kefu']);
        $url = $kefu_arr[array_rand($kefu_arr)];

        Log::write('点击事件1：请求->page:' . json_encode($data), 'info');
        Log::write('点击事件1-1：跳转地址:' . $url, 'info');

        //s2s 
        $page_log_arr = Db::table('page_log')->where('id', $aid)->find();
        $user_arr = Db::table('user')->where('usercode', $page_log_arr['usercode'])->find();
        $adjust_arr = Db::table('adjust')->where('adid', $user_arr['adid'])->find();
        $con_arr = json_decode($adjust_arr['content'], true);
        Log::write('点击事件-test-1：gps_adid:' . json_encode($con_arr), 'info');
        $gps_adid = array_key_exists('gps_adid', $con_arr) ? $con_arr['gps_adid'] : '';
        Log::write('点击事件-test：gps_adid:' . $gps_adid, 'info');
        // $campaign_name = array_key_exists('campaign_name', $con_arr) ? $con_arr['campaign_name'] : '';
        // $adgroup_name = array_key_exists('adgroup_name', $con_arr) ? $con_arr['adgroup_name'] : '';

        if ($appid) {
            $channel_arr = Db::table('channel')->where('number', $appid)->find();
            Log::write('点击事件2：channel:' . json_encode($channel_arr), 'info');
            $app_token = $channel_arr['app_token'];
            $event_token = $channel_arr['event_token'];
            $auto = $channel_arr['auto'];
        }
        $params['s2s'] = 1;
        $params['adid'] = $user_arr['adid'];
        $params['gps_adid'] = $gps_adid;
        $params['event_token'] = $event_token; //'giuhfr'; ;
        $params['app_token'] = $app_token; // 'dkl9dtyay96o';
        $params['callback_params'] = json_encode([
            'click' => '"' . $button . '"',
            // 'campaign_name' => $campaign_name,
            // 'adgroup_name' => $adgroup_name
        ]);

        $data_result = http_post('https://s2s.adjust.com/event', $params, true, $auto);
        $params_json = json_encode($params);
        Log::write('点击事件3：adjust-s2s 页面点击事件:' . $params_json . '   adjust返回：' . $data_result, 'info');

        Db::table('page_click_log')->insert([
            'page_keys' => $id,
            'page_log_id' => $aid,
            'button' => $button,
            'url' => $url,
            'param' => $params_json . '-' . $auto,
            'result' => $data_result,
            'create_time' => time()
        ]);
        echo '<script>window.location.href="' . $url . '"</script>';
        die;
    }
    /**
     * 注册
     */
    public function reg(Request $request)
    {
        $mobile = $request->post('mobile');
        if ($mobile == '12344321') {
            return json(['code' => 300, 'msg' => '注册成功']);
        }
        Log::write('注册入口1：' . json_encode($request->post()), 'info');
        $data = [
            'mobile' => $mobile,
            'nickname' => '用户' . rand(10000, 99999),
            'avatar' => '/static/images/avatar.png',
            'create_time' => time(),
        ];
        $res = Db::name('user')->where('usercode', $request->post('usercode'))->update($data);
        Log::write('注册入口2，改user表：' . json_encode($res), 'info');
        if ($res) {
            return json(['code' => 200, 'msg' => '注册成功']);
        } else {
            return json(['code' => 400, 'msg' => 'login has failed']);
        }
    }
    /**
     * 等待页面
     */
    public function next(Request $request)
    {
        $usercode = $request->param('usercode');

        $api_log_id = Db::table('api_log')->insertGetId([
            'code' => $usercode,
            'url' => $request->domain() . $request->url(),
            'result' => '打开页面:' . date('Y-m-d H:i:s') . '|',
            'create_time' => time(),
        ]);
        return view('', [
            'usercode' => $usercode,
            'apilogid' => $api_log_id,
        ]);
    }
    /**
     * 审核中转页面
     */
    public function feiyanzheng(Request $request)
    {
        $usercode = $request->param('usercode');
        $userData = Db::table('user')->where('usercode', $usercode)->find();
        $channelData = Db::table('channel')->where('number', $userData['appcode'])->find();
        echo '<script>window.location.href="' . $channelData['url'] . '";</script>';
        die;
    }

    /**
     * 判断adjust数据
     */
    public function adjust($uid)
    {
        $res = Db::name('user')->where('usercode', $uid)->find();
        Log::write('adjust验证1，用户数据：' . json_encode($res), 'info');
        if ($res) {
            $adid = $res['adid'];
            if ($adid) {
                $adres = Db::name('adjust')->where('adid', $adid)->find();
                Log::write('adjust验证2，数据：' . json_encode($adres), 'info');
                if ($adres['content'] != '') {
                    $adv_id = $adres['adv_id'];
                    if ($adv_id == 0) {   //广告归因无数据
                        return json(['code' => 100, 'msg' => 'A']);
                    }
                    $promotion_arr = Db::name('promotion')->where(['number' => $adv_id])->find();
                    Log::write('adjust验证4，promotion数据：' . json_encode($promotion_arr), 'info');
                    if (!$promotion_arr) { //归因数据不匹配
                        Log::write('adjust_有广告系列数据，配置无。' . $adv_id, 'info');
                        return json(['code' => 100, 'msg' => 'A']);
                    }

                    $url = $promotion_arr['url'] . '?usercode=' . $uid;  //B面地址
                    return json(['code' => 200, 'url' => $url, 'msg' => '已调整']);
                }
            }
        }
        return json(['code' => 400, 'msg' => '未调整']);
    }

    /**
     * 选项结果存储
     */
    public function saveResult(Request $request)
    {
        $param = $request->param();
        Db::table('wenjuan')->insert($param);
    }
}
